{include file="common/head"}
<style>
  .search-container {
    padding: 20px;
  }

  .layui-form-label {
    width: 100px;
  }
</style>

<body>
  <div class="search-container layui-form" lay-filter="search">
    <div class="layui-inline">
      <div class="layui-input-wrap">
        <div class="layui-input-prefix">
          <i class="layui-icon layui-icon-username"></i>
        </div>
        <input type="text" name="username" id="username" value="" placeholder="用户名" class="layui-input"
          lay-affix="clear">
      </div>
    </div>
    <div class="layui-inline">
      <label class="layui-form-label">注册时间</label>
      <div class="layui-inline" id="ID-laydate-range">
        <div class="layui-input-inline">
          <input type="text" autocomplete="off" id="ID-laydate-start-date" class="layui-input" placeholder="开始日期">
        </div>
        <div class="layui-form-mid">-</div>
        <div class="layui-input-inline">
          <input type="text" autocomplete="off" id="ID-laydate-end-date" class="layui-input" placeholder="结束日期">
        </div>
      </div>
    </div>
    <div class="layui-inline">
      <div class="layui-clear">
        <button style="float: right;" class="layui-btn layui-btn-sm layui-bg-blue" id="search">搜索用户</button>
      </div>
    </div>
  </div>
  <div style="padding: 16px;">
    <table class="layui-hide" id="test" lay-filter="test"></table>
  </div>
  <script type="text/html" id="toolbarDemo">
  <div class="layui-btn-container">
    <button class="layui-btn layui-btn-sm layui-bg-black" id="dropdownButton">
      操作 
      <i class="layui-icon layui-icon-down layui-font-12"></i>
    </button>
    <button class="layui-btn layui-btn-sm layui-bg-red" lay-event="delCheck">删除选中</button>
  </div>
 
</script>

  <script type="text/html" id="barDemo">
  <div class="layui-clear-space">
    <a class="layui-btn layui-btn-xs layui-bg-orange" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-xs layui-bg-gray" lay-event="more">
      更多 
      <i class="layui-icon layui-icon-down"></i>
    </a>
  </div>
</script>

  {include file="common/bottom"}

  <script>
    layui.use(function () {
      var table = layui.table;
      var dropdown = layui.dropdown;
      var laydate = layui.laydate;
      var upload = layui.upload;
      var element = layui.element;
      var $ = layui.$
      laydate.render({
        elem: '#ID-laydate-start-date',
      });
      laydate.render({
        elem: '#ID-laydate-end-date',
      });
      $('#search').click(() => {
        let username = $('#username').val()
        let start = $('#ID-laydate-start-date').val()
        let end = $('#ID-laydate-end-date').val()
        if (username == '' && start == '' && end == '') {
          table.reload('test', { where: { type: '' } })
        } else {
          table.reload('test', {
            where: {
              username: username
              , begin_time: start
              , end_time: end
              , type: 'search'
            },
          })
        }

      })
      function delUser(id) {
        $.ajax({
          url: '/admin/user/del/id/' + id
          , dataType: 'json'
          , success: (res) => {
            if (res.code == 200) {
              layer.msg('删除成功', { icon: 6 })
            } else {
              layer.msg('删除失败', { icon: 5 })
            }
          }
        })
      }

      // 创建渲染实例
      table.render({
        elem: '#test',
        url: '/admin/user/list/', // 此处为静态模拟数据，实际使用时需换成真实接口
        toolbar: '#toolbarDemo',
        parseData: function (res) { // res 即为原始返回的数据
          return {
            "code": res.code, // 解析接口状态
            "msg": res.msg, // 解析提示文本
            "count": res.count, // 解析数据长度
            "data": res.data.data
          };
        },
        defaultToolbar: ['filter', 'exports', 'print', { // 右上角工具图标
          title: '提示',
          layEvent: 'LAYTABLE_TIPS',
          icon: 'layui-icon-tips',
          onClick: function (obj) { // 2.9.12+
            layer.alert('自定义工具栏图标按钮');
          }
        }],
        height: 'full',
        css: [
          '.layui-table-tool-temp{padding-right: 145px;}'
        ].join(''),
        cellMinWidth: 80,
        totalRow: true, // 开启合计行
        page: true,
        cols: [[
          { type: 'checkbox' },
          { field: 'id', width: 80, title: 'ID', sort: true },
          { field: 'username', width: 80, title: '用户名' },
          { field: 'nickname', width: 80, title: '昵称' },
          { field: 'email', width: 130, title: '邮箱' },
          { field: 'score', width: 80, title: '积分', edit: 'num' },
          { field: 'signature', width: 230, title: '签名' },
          {
            field: 'role', width: 80, title: '角色', templet: function (d) {
              if (d.role == 'all') {
                return `<span class="layui-badge layui-bg-blue">站长</span>`
              } else if (d.role != '普通vip') {
                return `<span class="layui-badge layui-bg-red">${d.role}</span>`
              } else {
                return `<span class="layui-badge-rim">普通用户</span>`
              }
            }
          },
          { field: 'ip', width: 100, title: 'IP' },
          {
            field: 'status', width: 80, title: '状态', templet: function (d) {
              if (d.status == 1) {
                return '<span class="layui-badge layui-bg-blue">正常</span>'
              } else if (d.status == 0) {
                return '<span class="layui-badge layui-bg-red">封禁</span>'
              } else if (d.status == 2) {
                return '<span class="layui-badge layui-bg-orange">待审核</span>'
              } else {
                return '<span class="layui-badge layui-bg-purple">禁言中</span>'
              }
            }
          },
          { field: 'create_time', width: 80, title: '注册时间' },
          { title: '操作', width: 134, minWidth: 125, toolbar: '#barDemo' }
        ]],
        done: function () {
          var id = this.id;
          dropdown.render({
            elem: '#dropdownButton', // 可绑定在任意元素中，此处以上述按钮为例
            data: [{
              id: 'add',
              title: '添加用户'
            }, {
              id: 'examine',
              title: '一键审核'
            },],
            // 菜单被点击的事件
            click: function (obj) {
              var checkStatus = table.checkStatus(id)
              var data = checkStatus.data; // 获取选中的数据
              switch (obj.id) {
                case 'add':
                  layer.open({
                    title: '添加用户',
                    type: 2,
                    area: ['80%', '80%'],
                    resize: false,
                    shadeClose: true,
                    content: '/admin/user/add'

                  })
                  break

                case 'examine':
                  var getData = table.getData(id);
                  let examUser = ''
                  let con = layer.confirm('确定要【一键审核】吗？', () => {
                    $.get('/admin/user/examineAll', (res) => {
                      if (res.code == 200) {
                        layer.msg('操作成功', { time: 500 })
                        table.reload('test')
                      } else {
                        layer.msg('操作失败', { time: 500 })
                      }
                    })
                    layer.close(con)
                  })
                  break
              }
            }
          })

        },
        error: function (res, msg) {
          console.log(res, msg)
        }
      });



      // 触发单元格工具事件
      table.on('tool(test)', function (obj) { // 
        var data = obj.data; // 获得当前行数据
        // console.log(obj)
        if (obj.event === 'edit') {
          layer.open({
            title: '编辑用户 [' + data.id + '] ',
            type: 2,
            area: ['80%', '80%'],
            content: '/admin/user/update/id/' + data.id
          });
        } else if (obj.event === 'more') {
          // 更多 - 下拉菜单
          dropdown.render({
            elem: this, // 触发事件的 DOM 对象
            show: true, // 外部事件触发即显示
            data: [{
              title: '查看',
              id: 'detail'
            }, {
              title: '审核',
              id: 'examine'
            }, {
              title: '删除',
              id: 'del'
            }],
            click: function (menudata) {
              if (menudata.id === 'detail') {
                layer.open({
                  title: `用户[${data.username}]`
                  , area: ['80%', '80%']
                  , type: 2
                  , shadeClose: true
                  , maxmin: true
                  , anim: 1
                  , content: `/index/profile/index.html?uid=${data.id}`
                })
              } else if (menudata.id === 'del') {
                layer.confirm('真的删除行 [id: ' + data.id + '] 么', function (index) {
                  obj.del(); // 删除对应行（tr）的DOM结构
                  layer.close(index);
                  delUser(data.id)
                });
              } else if (menudata.id == 'examine') {
                $.post('/admin/user/doUpdate', { status: 1, id: data.id }, (res) => {
                  if (res.code == 200) {
                    layer.msg('审核成功')
                  }else{
                    layer.msg('审核失败')
                  }
                })
              }
            },
            align: 'right', // 右对齐弹出
            style: 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);' // 设置额外样式
          })
        }
      });
      // 工具栏事件
      table.on('toolbar(test)', function (obj) {
        var id = obj.config.id;
        var checkStatus = table.checkStatus(id);
        var othis = lay(this);
        switch (obj.event) {
          case 'add':
            layer.open({
              title: '添加用户',
              type: 2,
              area: ['80%', '80%'],
              resize: false,
              shadeClose: true,
              content: '/admin/user/add'

            })
            break;
          case 'examine':
            var getData = table.getData(id);
            let examUser = ''
            let con = layer.confirm('确定要【一键审核】吗？', () => {
              $.get('/admin/user/examineAll', (res) => {
                if (res.code == 200) {
                  layer.msg('操作成功', { time: 500 })
                  table.reload('test')
                } else {
                  layer.msg('操作失败', { time: 500 })
                }
              })
              layer.close(con)
            })
            break
          case 'delCheck':
            var options = obj.config;
            checkStatus = table.checkStatus(options.id);
            checkStatus.data.forEach(el => {
              $.get('/admin/user/del', { id: el.id })
            });
            table.reload('test')
            layer.msg('操作成功', { time: 500 })
            break
        };
      });
      // 触发表格复选框选择
      table.on('checkbox(test)', function (obj) {

      });

      // 行单击事件
      table.on('row(test)', function (obj) {
        console.log(obj);
        //layer.closeAll('tips');
      });
      // 行双击事件
      table.on('rowDouble(test)', function (obj) {
        console.log(obj);
      });

      // 单元格编辑事件
      table.on('edit(test)', function (obj) {
        var field = obj.field; // 得到字段
        var value = obj.value; // 得到修改后的值
        var data = obj.data; // 得到所在行所有键值
        // 值的校验
        if (field == 'score') {
          var regPos = /^[0-9]+.?[0-9]*/
          if (!regPos.test(obj.value)) {
            layer.tips('输入的【积分】数量格式应为数字', this, { tips: 1 });
            return obj.reedit();
          } else {
            $.ajax({
              url: '/admin/user/doUpdate'
              , type: 'post'
              , data: {
                id: data.id
                , score: obj.value
              }
              , dataType: 'json'
              , success: (res) => {
                console.log(res);
                /*  if (res.code == 200) {
                   layer.msg('修改成功', { icon: 6 })
                 } else {
                   layer.msg('删除失败', { icon: 5 })
                 }
*/
              }
            })
          }
        }

        layer.msg('编辑成功', { icon: 1 });

        // 其他更新操作
        var update = {};
        update[field] = value;
        obj.update(update);
      });
    });
  </script>
</body>

</html>